import 'package:flutter/material.dart';
import 'package:kiomax/utils/common_util.dart';
import '../../config/string_config.dart';
import '../../config/color_config.dart';
import '../../config/text_style_config.dart';
import '../../widgets/title/title_widget.dart';

class LocationCreatePage extends StatefulWidget {
  const LocationCreatePage({Key? key}) : super(key: key);

  @override
  State<LocationCreatePage> createState() => _LocationCreatePageState();
}

class _LocationCreatePageState extends State<LocationCreatePage> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  final _formKey = GlobalKey<FormState>();
  // 控制展开/收起
  bool _advancedOpen = false;
  // 控制开关
  bool _onPremises = false;
  Map<String, bool> _paymentTypes = {
    'Mobile App': false,
    'Credit/Debit Card': false,
    'Coin': false,
    'Game Card': true,
    'Campus Solution': false,
  };
  // 下拉选项
  String? _state;
  String? _paymentGateway;
  String? _paymentMode;
  String? _language;
  String? _campusSolution;

  // 控制器
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _cityController = TextEditingController();
  final TextEditingController _address1Controller = TextEditingController();
  final TextEditingController _address2Controller = TextEditingController();
  final TextEditingController _zipController = TextEditingController();
  final TextEditingController _contactNameController = TextEditingController();
  final TextEditingController _contactNumberController =
      TextEditingController();
  final TextEditingController _contactEmailController = TextEditingController();

  @override
  void dispose() {
    _nameController.dispose();
    _cityController.dispose();
    _address1Controller.dispose();
    _address2Controller.dispose();
    _zipController.dispose();
    _contactNameController.dispose();
    _contactNumberController.dispose();
    _contactEmailController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: TitleWidget(
          isHome: true, context: context, scaffoldKey: _scaffoldKey),
      backgroundColor: ColorConfig.white,
      body: SafeArea(
        child: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
            child: Form(
              key: _formKey,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _buildTitle(),
                  const SizedBox(height: 16),
                  _buildProgressBar(),
                  const SizedBox(height: 32),
                  _buildRequiredInput(_nameController, 'Location Name'),
                  const SizedBox(height: 24),
                  _buildDropdown('State / Province', _state,
                      ['State1', 'State2'], (v) => setState(() => _state = v)),
                  const SizedBox(height: 24),
                  _buildRequiredInput(_cityController, 'City'),
                  const SizedBox(height: 24),
                  _buildRequiredInput(_address1Controller, 'Address Line 1'),
                  const SizedBox(height: 24),
                  _buildInput(_address2Controller, 'Address Line 2'),
                  const SizedBox(height: 24),
                  _buildRequiredInput(_zipController, 'Postal/Zip Code'),
                  const SizedBox(height: 24),
                  _buildInput(_contactNameController, 'Contact Name'),
                  const SizedBox(height: 24),
                  _buildInput(_contactNumberController, 'Contact Number'),
                  const SizedBox(height: 24),
                  _buildInput(_contactEmailController, 'Contact Email Address'),
                  const SizedBox(height: 24),
                  _buildDropdown(
                      'Payment Gateway',
                      _paymentGateway,
                      ['TSYS - Summit', 'Other'],
                      (v) => setState(() => _paymentGateway = v)),
                  const SizedBox(height: 32),
                  _buildAdvancedSettings(),
                  const SizedBox(height: 32),
                  _buildPaymentTypes(),
                  const SizedBox(height: 32),
                  _buildDropdown(
                      'Campus Solution',
                      _campusSolution,
                      ['None', 'Option1'],
                      (v) => setState(() => _campusSolution = v)),
                  const SizedBox(height: 32),
                  _buildConfirmButton(),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildTitle() {
    return Text(
      'Create New Location',
      style: TextStyleConfig.heading20.copyWith(
        color: const Color(0xFF002B66),
        fontWeight: FontWeight.w700,
        fontSize: 22,
      ),
      textAlign: TextAlign.left,
    );
  }

  Widget _buildProgressBar() {
    return Stack(
      alignment: Alignment.centerLeft, // 让内容在左边对齐
      children: [
        Container(
          width: double.infinity,
          height: 20,
          decoration: BoxDecoration(
            color: ColorConfig.progresssunselected,
            borderRadius: BorderRadius.circular(40),
          ),
        ),
        Container(
          height: 20,
          width: MediaQuery.of(context).size.width * 0.4,
          decoration: BoxDecoration(
            color: const Color(0xFF002B66),
            borderRadius: BorderRadius.circular(40),
          ),
        ),
        Positioned(
          left: MediaQuery.of(context).size.width * 0.4 - 20, // 9 = half of circle (18 / 2)
          child: Container(
            width: 18,
            height: 18,
            decoration: BoxDecoration(
              color: Colors.white,
              shape: BoxShape.circle,
              border: Border.all(color: const Color(0xFFCCE1FF), width: 3),
            ),
          ),
        ),
      ],
    )
    ;
  }

  Widget _buildRequiredInput(TextEditingController controller, String label) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            const Text('*', style: TextStyle(color: Colors.red)),
            const SizedBox(width: 2),
            Text(label, style: TextStyleConfig.itemLabel),
          ],
        ),
        const SizedBox(height: 8),
        _buildInputBox(controller),
      ],
    );
  }

  Widget _buildInput(TextEditingController controller, String label) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(label, style: TextStyleConfig.itemLabel),
        const SizedBox(height: 8),
        _buildInputBox(controller),
      ],
    );
  }

  Widget _buildInputBox(TextEditingController controller) {
    return SizedBox(
      height: 48,
      child: TextField(
        controller: controller,
        style: const TextStyle(fontSize: 16),
        decoration: InputDecoration(
          hintText: '',
          hintStyle: const TextStyle(
            color: Color(0xFFBDBDBD),
            fontSize: 16,
          ),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(8),
            borderSide: const BorderSide(color: Color(0xFFE0E0E0)),
          ),
          enabledBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(8),
            borderSide: const BorderSide(color: Color(0xFFE0E0E0)),
          ),
          focusedBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(8),
            borderSide: const BorderSide(color: Color(0xFF002B66)),
          ),
          contentPadding:
              const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
        ),
      ),
    );
  }

  Widget _buildDropdown(String label, String? value, List<String> items,
      ValueChanged<String?> onChanged) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(label, style: TextStyleConfig.itemLabel),
        const SizedBox(height: 8),
        SizedBox(
          height: 48,
          child: DropdownButtonFormField<String>(
            value: value,
            items: items
                .map((e) => DropdownMenuItem(value: e, child: Text(e)))
                .toList(),
            onChanged: onChanged,
            decoration: InputDecoration(
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
                borderSide: const BorderSide(color: Color(0xFFE0E0E0)),
              ),
              enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
                borderSide: const BorderSide(color: Color(0xFFE0E0E0)),
              ),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
                borderSide: const BorderSide(color: Color(0xFF002B66)),
              ),
              contentPadding:
                  const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildAdvancedSettings() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        GestureDetector(
          onTap: () => setState(() => _advancedOpen = !_advancedOpen),
          child: Row(
            children: [
              Expanded(
                child: Text('Advanced Settings',
                    style: TextStyleConfig.heading20.copyWith(
                        fontSize: 16, color: ColorConfig.titleTextColor)),
              ),
              Icon(_advancedOpen ? Icons.expand_less : Icons.expand_more,
                  color: ColorConfig.titleTextColor),
            ],
          ),
        ),
        if (_advancedOpen) ...[
          const SizedBox(height: 16),
          _buildDropdown('Payment Mode', _paymentMode, ['Value', 'Other'],
              (v) => setState(() => _paymentMode = v)),
          const SizedBox(height: 16),
          _buildDropdown('Language', _language, ['English', 'Other'],
              (v) => setState(() => _language = v)),
          const SizedBox(height: 16),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text('On-premises Server', style: TextStyleConfig.itemLabel),
              Switch(
                value: _onPremises,
                onChanged: (v) => setState(() => _onPremises = v),
                activeColor: const Color(0xFF002B66),
              ),
            ],
          ),
        ]
      ],
    );
  }

  Widget _buildPaymentTypes() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Payment Types',
            style: TextStyleConfig.heading20
                .copyWith(fontSize: 16, color: ColorConfig.titleTextColor)),
        const SizedBox(height: 16),
        ..._paymentTypes.keys
            .map((k) => Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(k, style: TextStyleConfig.itemLabel),
                    Switch(
                      value: _paymentTypes[k]!,
                      onChanged: (v) => setState(() => _paymentTypes[k] = v),
                      activeColor: const Color(0xFF002B66),
                    ),
                  ],
                ))
            .toList(),
      ],
    );
  }

  Widget _buildConfirmButton() {
    return SizedBox(
      width: double.infinity,
      height: 48,
      child: ElevatedButton(
        style: ElevatedButton.styleFrom(
          backgroundColor: const Color(0xFF002B66),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(40),
          ),
          padding: EdgeInsets.zero,
        ),
        onPressed: () {
          // TODO: 提交逻辑
          CommonUtil.showTipDialog(context,title: StringConfig.creating_location,message: StringConfig.creating_location_tip);
        },
        child: Text(
          'Confirm',
          style: TextStyleConfig.buttonText.copyWith(
              fontSize: 20, fontWeight: FontWeight.bold, color: Colors.white),
        ),
      ),
    );
  }
}
